//
//  ViewController.m
//  OCAndJS
//
//  Created by  Mac on 2017/8/8.
//  Copyright © 2017年  Mac. All rights reserved.
//

#import "ViewController.h"

#import "CustomImgCtrl.h"

#import <JavaScriptCore/JavaScriptCore.h>

#import "SaveImage_Util.h"

#define ORIGINAL_MAX_WIDTH 640.0f

#define APP_WIDTH  [[UIScreen mainScreen] bounds].size.width

#define APP_HEIGHT [[UIScreen mainScreen] bounds].size.height

#define AppColor  [UIColor  orangeColor]

@interface ViewController ()<UIWebViewDelegate,UIActionSheetDelegate,CustomImgDelegate,UIActionSheetDelegate>

@property(nonatomic,strong)UIWebView * webView;

@property(nonatomic,strong)JSContext * jsContext;


//车型
@property(nonatomic,strong)NSString * carType;

@property(nonatomic,strong)UIImageView *imageForUpLoad;

@property(nonatomic,strong)NSString * stringForElementName;

@end

@implementation ViewController

- (instancetype)initWithTitle:(NSString *)titleString urlString:(NSString *)urlString
{
    self = [super init];
    if (self) {
        self.webTitleString = titleString;
        self.webUrlString = urlString;
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)titleString localResourceName:(NSString *)localResourceName
{
    self = [super init];
    if (self) {
        self.webTitleString = titleString;
        self.webLocalResourceName = localResourceName;
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)titleString htmlString:(NSString *)htmlString
{
    self = [super init];
    if (self) {
        self.webTitleString = titleString;
        self.webHTMLString = htmlString;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self createNav];
    
    self.navigationItem.title = self.webTitleString;
    
    // initUI
    [self initUI];
    
    // 开始加载数据
    [self startLoad];
    
    
    [self test];
    
}



-(void)test
{
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    
    context[@"getPic"] = ^(NSString * str) {
        
        _stringForElementName = str;
        
        [self resetHeadImageView];
        
        
        //
        //        //        // 将结果返回给js
        //
        //        JSContext *context1=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        //
        //        NSString *imgB64 = [UIImageJPEGRepresentation(image, 0.8) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        //        NSString *source = [NSString stringWithFormat:@"data:image/png;base64,%@", imgB64];
        //
        //        JSValue * jsValue = context1[@"getPicCallback2"];
        //        [jsValue callWithArguments:@[@{@"changeImage":source}]];
        
        
        //注释掉的内容 - 129
        
        //        UIImage * image = [UIImage imageNamed:@"driver_chat"];
        //
        //        JSContext *context1=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        //
        //        NSString *imgB64 = [UIImageJPEGRepresentation(image, 0.8) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        //
        //        NSString *source = [NSString stringWithFormat:@"data:image/png;base64,%@", imgB64];
        //
        //
        //        JSValue * jsValue = context1[@"getPicCallback2"];
        //        [jsValue callWithArguments:@[@{@"elementName":_stringForElementName},@{@"changeImage":source},@{@"imageForOther":str}]];
        
        
        
        
    };
    
}
-(void)createNav
{
    UIView * headView = [[UIView alloc] init];
    headView.frame = CGRectMake(0, 0, APP_WIDTH, 64);
    headView.backgroundColor = AppColor;
    [self.view addSubview:headView];
    
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(60, 10, APP_WIDTH - 120, 54);
    titleLabel.font = [UIFont systemFontOfSize:17];
    titleLabel.text = self.webTitleString;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor blackColor];
    [headView addSubview:titleLabel];
    
    UIButton * backBtn = [[UIButton alloc] init];
    backBtn.frame = CGRectMake(10, 25, 25, 25);
    [backBtn setImage:[UIImage imageNamed:@"nav_left_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:backBtn];
    
    UIView * navBottomLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 63, APP_WIDTH, 1)];
    navBottomLineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [headView addSubview:navBottomLineView];
    
}






-(void)backAction
{
//    SAVEDEFAULTS(@"0",KuaiCheStatus)
//    [self.navigationController popToRootViewControllerAnimated:NO];
}

- (void)initUI
{
    UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, APP_WIDTH, APP_HEIGHT - 64)];
    webView.delegate = self;
    [self.view addSubview:webView];
    self.webView = webView;
}

#pragma mark 开始加载数据
- (void)startLoad
{
    // 加载网页
    if (self.webUrlString) {
        NSURL* url = [NSURL URLWithString:self.webUrlString];
        NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
        [self.webView loadRequest:request];
    }
    
    // 加载本地html文件
    else if (self.webLocalResourceName){
        NSString* path = [[NSBundle mainBundle] pathForResource:self.webLocalResourceName ofType:@"html"];
        NSURL* url = [NSURL fileURLWithPath:path];
        NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
        [self.webView loadRequest:request];
    }
    
    // 加载html字符串
    else if (self.webHTMLString){
        [self.webView loadHTMLString:self.webHTMLString baseURL:nil];
    }
}

#pragma mark webViewDelegate

// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

// 结束加载
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //self.jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
}

// 开始加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    
    //截获字符串方法
    NSString *url = request.URL.absoluteString;
    
    NSString *schemew = @"akcome://";
    if ([url hasPrefix:schemew]) {
        NSString *methodName = [url substringFromIndex:schemew.length];
        [self performSelector:NSSelectorFromString(methodName) withObject:nil];
        
    }
    
    //    控件修改值的方法
    //    UIImage * image = [UIImage imageNamed:@"way_bg"];
    //
    //    NSString *imgB64 = [UIImageJPEGRepresentation(image, 1.0) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //    NSString *source = [NSString stringWithFormat:@"data:image/png;base64,%@", imgB64];
    //
    
    return YES;
    
}

-(void)IdCard{
    
    
    //    NSLog(@"123123132");
    //    NSString * string1 = @"sdfasdfas";
    //    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //    NSString *jsStr = [NSString stringWithFormat:@"getPicCallback2('%@')",string1];
    //     [context evaluateScript:jsStr];
    return;
}




//重设图片
-(void)resetHeadImageView{
    //    NSLog(@"修改头像")
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"上传图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self startUsingCamera];
        
    }];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self startUsingAlbum];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:camera];
    [alert addAction:album];
    [alert addAction:cancel];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:nil];
    });
    
    
    
    
    
}
//启用相机
-(void)startUsingCamera{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *pickerCtl = [[UIImagePickerController alloc]init];
        pickerCtl.delegate = self;
        pickerCtl.allowsEditing = YES;
        pickerCtl.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:pickerCtl animated:YES completion:nil];
    }
}
//启用相册
-(void)startUsingAlbum{
    UIImagePickerController *pickerCtl=[[UIImagePickerController alloc]init];
    pickerCtl.delegate = self;
    pickerCtl.allowsEditing = YES;
    pickerCtl.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:pickerCtl animated:YES completion:nil];
}
/** 压缩图片 */
-(UIImage *)thumbnaiWithImage:(UIImage *)image size:(CGSize)size{
    UIImage *newImage = nil;
    if (image!=nil) {
        //获取 要开始绘制的图片（尺寸大小）的上下文
        UIGraphicsBeginImageContext(size);
        //绘制size大小的图片
        [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
        //从现在绘制的图片 的上下文中 获取绘制好的图片
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        //关闭 绘制图片的上下文
        UIGraphicsEndImageContext();
    }
    return newImage;
}
/** 对imageView进行图片压缩，并给Imv赋值 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //获取 原始图片
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    //进行图片压缩，尺寸
    //    UIImage *compressImage = [self thumbnaiWithImage:originalImage size:CGSizeMake(170, 170)];
    
    //将压缩的图片 转化为 NSData，以便上传 头像信息,缩小为0.1倍
    //    NSData *imageData = UIImageJPEGRepresentation(compressImage, 0.8);
    
    //    UIImage * image = [UIImage imageNamed:@"driver_chat"];
    
    //        // 将结果返回给js
    
    NSData *data = UIImagePNGRepresentation(originalImage);
    NSString *str = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    
    
    NSString *nameStr = [NSString stringWithFormat:@"%@.jpg",_stringForElementName];
    //    [SaveImage_Util saveImage:originalImage ImageName:nameStr back:^(NSString *imagePath) {
    //        dispatch_async(dispatch_get_main_queue(), ^{
    ////            NSLog(@"图片路径：%@",imagePath);
    ////            /**
    ////             *  这里是IOS 调 js 其中 setImageWithPath 就是js中的方法 setImageWithPath(),参数是字典
    ////             */
    ////            JSValue *jsValue = self.jsContext[@"setImageWithPath"];
    ////            [jsValue callWithArguments:@[@{@"imagePath":imagePath,@"iosContent":@"获取图片成功，把系统获取的图片路径传给js 让html显示"}]];
    //
    //
    //            JSContext *context1=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //
    //            NSString *imgB64 = [UIImageJPEGRepresentation(originalImage, 0.8) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //
    //            NSString *source = [NSString stringWithFormat:@"data:image/png;base64,%@", imgB64];
    //
    //
    //
    //            JSValue * jsValue = context1[@"getPicCallback2"];
    //            [jsValue callWithArguments:@[@{@"elementName":_stringForElementName},@{@"changeImage":source},@{@"imageForOther":str}]];
    //
    //
    //
    //        });
    //    }];
    
    JSContext *context1=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    NSString *imgB64 = [UIImageJPEGRepresentation(originalImage, 0.5) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSString *source = [NSString stringWithFormat:@"data:image/png;base64,%@", imgB64];
    
    
    
    JSValue * jsValue = context1[@"getPicCallback2"];
    [jsValue callWithArguments:@[@{@"elementName":_stringForElementName},@{@"changeImage":source},@{@"imageForOther":str}]];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageCropperDidCancel:(CustomImgCtrl *)cropperViewController
{
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}


//截获图片事件的代理方法
- (void)imageCropper:(CustomImgCtrl *)cropperViewController didFinished:(UIImage *)editedImage
{
    NSLog(@"截获时间 ............................");
}


-(void)doatest
{
    NSLog(@"do a test success");
}

-(void)dobtest
{
    NSLog(@"do b test success ");
    //    [self shootPiicturePrVideo];
}

-(void)doctest
{
    NSLog(@"do a test success ");
}


-(void)dodtest
{
    NSLog(@"do a test success ");
}


- (void)showMsg:(NSString *)message {
    // [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
}


-(void)funtionForWeChat
{
    //    NSLog(@"监听到这个方法了 .........................");
    //    // 底部提示框
    //    UIAlertControllerStyleActionSheet
    //    // 中部提示框
    //    UIAlertControllerStyleAlert
    
    //    UIAlertActionStyleDefault, //默认
    //    UIAlertActionStyleCancel, //取消
    //    UIAlertActionStyleDestructive //警告
    
    //    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"传成功了" message:nil preferredStyle:UIAlertControllerStyleAlert];
    //    
    //    [alert addAction:[UIAlertAction actionWithTitle:@"123" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //    }]];
    //    
    //    [self presentViewController:alert animated:YES completion:nil];
    
}



@end
